

package top.continew.admin.controller.question;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.continew.admin.common.context.UserContextHolder;
import top.continew.admin.question.dify.workflow.QuestionWorkflow;

import top.continew.admin.question.dify.workflow.req.AiJudgeKnowledge;
import top.continew.admin.question.dify.workflow.req.QuestionAnswerReq;
import top.continew.admin.question.dify.workflow.req.QuestionGenerateReq;
import top.continew.admin.question.manger.base.HttpKit;
import top.continew.admin.question.manger.service.model.*;
import top.continew.admin.question.dto.QuestionErrorCorrectionQueryDto;
import top.continew.admin.question.manger.service.PointService;
import top.continew.admin.question.manger.service.QuestionErrorCorrectionService;
import top.continew.admin.question.manger.service.MangerQuestionService;
import top.continew.starter.core.validation.ValidationUtils;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.log.annotation.Log;
import top.continew.starter.web.model.R;

import java.util.List;

@Log(module = "题目")
@Tag(name = "题目 API")
@RequestMapping("question")
@RestController
public class QuestionController {

    @Autowired
    private QuestionErrorCorrectionService questionErrorCorrectionService;

    private MangerQuestionService mangerQuestionService;

    private PointService pointService;

    public QuestionController(MangerQuestionService mangerQuestionService, PointService pointService) {
        this.mangerQuestionService = mangerQuestionService;
        this.pointService = pointService;
    }

    @PostMapping
    public R saveQuestion(@RequestBody SaveQuestion saveQuestion) throws Exception {
        return R.ok(mangerQuestionService.save(saveQuestion));
    }

    @GetMapping
    public PageResp getList(QueryQuestion queryQuestion) throws Exception {
        return new PageResp(mangerQuestionService.getList(queryQuestion), (Long)HttpKit.getRequest()
            .getAttribute("total"));
    }

    @Log(ignore = true)
    @GetMapping("imageQuestionWorkflow")
    public R questionWorkflow(@RequestParam String fileUrl, @RequestParam Long subjectId) throws Exception {
        List<SaveQuestion> saveQuestions = QuestionWorkflow.imageQuestionWorkflow(fileUrl);
        for (SaveQuestion saveQuestion : saveQuestions) {
            saveQuestion.setSubjectId(subjectId);
            SaveQuestion question = mangerQuestionService.save(saveQuestion);
            if (saveQuestion.getSubQuestions() != null) {
                for (SaveQuestion subQuestion : saveQuestion.getSubQuestions()) {
                    subQuestion.setSubjectId(subjectId);
                    subQuestion.setParentId(question.getId());
                    mangerQuestionService.save(subQuestion);
                }
            }
        }
        return R.ok();
    }

    @Log(ignore = true)
    @PostMapping("aiAnalyze")
    public SaveQuestion aiAnalyze(@RequestBody QuestionAnswerReq questionAnswerReq) throws Exception {
        return QuestionWorkflow.questionAnswerWorkflow(questionAnswerReq);
    }

    @Log(ignore = true)
    @PostMapping("aiJudgeKnowledge")
    public List<String> aiJudgeKnowledge(@RequestBody AiJudgeKnowledge aiJudgeKnowledge) throws Exception {
        return QuestionWorkflow.questionKnowledgeWorkflow(aiJudgeKnowledge.getQuestion(), aiJudgeKnowledge
            .getKnowledgePoints());
    }

    /**
     * 根据知识点生成题目的工作流接口
     * 
     * @param questionGenerateReq 包含知识点、类目、数量和题目类型的请求参数
     * @return 生成的题目列表
     * @throws Exception 工作流执行异常
     */
    @PostMapping("questionGenerateWorkflow")
    public R questionGenerateWorkflow(@RequestBody QuestionGenerateReq questionGenerateReq) throws Exception {
        // 参数校验
        ValidationUtils.throwIf(questionGenerateReq.getKnowledge() == null || questionGenerateReq.getKnowledge()
            .trim()
            .isEmpty(), "知识点不能为空");
        ValidationUtils.throwIf(questionGenerateReq.getType() == null || questionGenerateReq.getType()
            .trim()
            .isEmpty(), "类目不能为空");
        ValidationUtils.throwIf(questionGenerateReq.getSum() == null || questionGenerateReq.getSum() <= 0, "数量必须大于0");
        ValidationUtils.throwIf(questionGenerateReq.getQuestionType() == null || questionGenerateReq.getQuestionType()
            .trim()
            .isEmpty(), "题目类型不能为空");

        return R.ok(QuestionWorkflow.questionGenerateWorkflow(questionGenerateReq));
    }

    @PutMapping("{id}:online")
    public R online(@PathVariable Long id, @RequestParam Long onlineStatus) throws Exception {
        mangerQuestionService.online(id, onlineStatus);
        return R.ok();
    }

    @GetMapping("spotCheck")
    public R getSpotCheckQuestionList(QuerySpotCheckQuestion querySpotCheckQuestion) throws Exception {
        return R.ok(mangerQuestionService.getSpotCheckQuestionList(querySpotCheckQuestion));
    }

    @GetMapping("spotCheckSum")
    public R getSpotCheckQuestionSum(QuerySpotCheckQuestion querySpotCheckQuestion) throws Exception {
        return R.ok(mangerQuestionService.getSpotCheckQuestionSum(querySpotCheckQuestion));
    }

    @GetMapping("id:{id}")
    public R getQuestionInfo(@PathVariable Long id) throws Exception {
        return R.ok(mangerQuestionService.getInfo(id));
    }

    @DeleteMapping("{questionId}")
    public R delete(@PathVariable String questionId) throws Exception {
        mangerQuestionService.delete(questionId);
        return R.ok();
    }

    @PutMapping("{questionId}/commitCheck")
    public R commitCheck(@PathVariable Long questionId, Long checkPeople) throws Exception {
        mangerQuestionService.commitCheck(questionId, checkPeople);
        return R.ok();
    }

    @PutMapping("{questionId}/rejectCheck")
    public R rejectCheck(@PathVariable Long questionId, @RequestParam String msg) throws Exception {
        mangerQuestionService.rejectCheck(questionId, msg);
        return R.ok();
    }

    @PutMapping("/rejectCheckMultiple")
    public R rejectCheckMultiple(@RequestBody RejectMultipleDto dto) throws Exception {

        mangerQuestionService.rejectCheckMultiple(dto.getIds(), dto.getMsg());
        return R.ok();
    }

    @PutMapping("{questionId}/commitReview")
    public R commitReview(@PathVariable Long questionId, Long reviewPeople) throws Exception {
        mangerQuestionService.commitReview(questionId, reviewPeople);
        return R.ok();
    }

    @PutMapping("{questionId}/rejectReview")
    public R rejectReview(@PathVariable Long questionId, @RequestParam String msg) throws Exception {
        mangerQuestionService.rejectReview(questionId, msg);
        return R.ok();
    }

    @PutMapping("{questionId}/review")
    public R review(@PathVariable Long questionId) throws Exception {
        mangerQuestionService.review(questionId);
        return R.ok();
    }

    @PutMapping("{questionId}/sort")
    public R questionSort(@PathVariable Long questionId, @RequestParam Long sort) throws Exception {
        mangerQuestionService.questionSort(questionId, sort);
        return R.ok();
    }

    @GetMapping("{questionId}/point")
    public R questionPoint(@PathVariable Long questionId) throws Exception {
        return R.ok(pointService.getQuestionPointList(questionId));
    }

    //    @PutMapping("{questionId}/point/{pointId}")
    //    public R addQuestionPoint(@PathVariable Long questionId,
    //                              @PathVariable Long pointId,
    //                              @RequestParam String name) throws Exception {
    //        pointService.addQuestionCorrelationPoint(questionId, pointId, name);
    //        return R.ok();
    //    }

    @PutMapping("{questionId}/point/{pointId}/sort")
    public R pointSort(@RequestParam Long sort,
                       @PathVariable String questionId,
                       @PathVariable String pointId) throws Exception {
        pointService.pointSort(questionId, pointId, sort);
        return R.ok();
    }

    //    @DeleteMapping("{questionId}/point/{pointId}")
    //    public R deleteQuestionPoint(@PathVariable String questionId, @PathVariable String pointId) throws Exception {
    //        pointService.deleteQuestionCorrelationPoint(questionId, pointId);
    //        return R.ok();
    //    }

    /**
     * 录题统计查询接口
     *
     * @return
     * @throws Exception
     */

    @GetMapping(value = "/statistical/teacher")
    public R statisticalTeacher(@RequestParam(value = "startTime", required = false) String startTime,
                                @RequestParam(value = "endTime", required = false) String endTime,
                                @RequestParam(value = "teacherId", required = false) Long teacherId) throws Exception {
        return R.ok(mangerQuestionService.statisticalTeacher(startTime, endTime, teacherId));
    }

    /**
     * 录题统计查询接口
     *
     * @return
     * @throws Exception
     */

    @GetMapping(value = "/statistical/paper/teacher")
    public R statisticalPaperTeacher(@RequestParam(value = "startTime", required = false) String startTime,
                                     @RequestParam(value = "endTime", required = false) String endTime,
                                     @RequestParam(value = "teacherId", required = false) Long teacherId) throws Exception {
        return R.ok(mangerQuestionService.statisticalPaperTeacher(startTime, endTime, teacherId));
    }

    /**
     * 题库管理查询接口(调整)
     *
     * @return
     * @throws Exception
     */

    @PostMapping(value = "/questionManager")
    public R questionManager(@RequestBody QuestionQuery query) throws Exception {
        return R.ok(mangerQuestionService.getListQuestionManager(query));
    }

    /**
     * 批量驳回审核接口
     *
     * @return
     * @throws Exception
     */

    @PostMapping(value = "/rejectReviewMultiple")
    public R rejectReviewMultiple(@RequestParam(value = "questionIds") String questionIds,
                                  @RequestParam(value = "msg", required = false) String msg) throws Exception {
        mangerQuestionService.rejectReviewMultiple(questionIds, msg);
        return R.ok();
    }

    /**
     * 获取题目上一条和下一条
     *
     * @param questionId
     * @param activeName
     * @return
     * @throws Exception
     */

    @GetMapping(value = "/questionUpAndDown")
    public R questionUpAndDown(@RequestParam(value = "questionId", required = false) Long questionId,
                               @RequestParam(value = "activeName", required = false) String activeName) throws Exception {
        return R.ok(mangerQuestionService.getQuestionUpAndDown(questionId, activeName));
    }

    @DeleteMapping(value = "/delQuestionAll")
    public R delQuestionAll(@RequestBody DelQuery delQuery) throws Exception {
        ValidationUtils.throwIf(delQuery.getIds() == null || delQuery.getIds().isEmpty(), "请选择需要删除的题目");
        return R.ok(mangerQuestionService.delQuestion(delQuery.getIds(), UserContextHolder.getUserId()));
    }

    @GetMapping("questionErrorCorrectionPage")
    public R questionErrorCorrection(QuestionErrorCorrectionQueryDto queryDto) {
        try {
            return R.ok(questionErrorCorrectionService.pageList(queryDto));
        } catch (Exception e) {
            return R.ok();
        }
    }

    @PostMapping("acceptStatus")
    public R acceptStatus(@RequestParam(value = "id") Long id) {
        try {
            questionErrorCorrectionService.acceptStatus(id);
            return R.ok();
        } catch (Exception e) {
            return R.ok();
        }
    }
}
